package com.wsc.wisdomchinaqinghe.Tools;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;
import android.view.WindowManager;
import android.widget.EditText;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.constant.Constant;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import cn.sharesdk.onekeyshare.OnekeyShare;
//http://encode.chahuo.com/?nsukey=UiFcJ7WhC39VOZkJ3BQ0PbQQSVwd%2F%2Fza8nVNW%2B5fEOtMoZgVbJPXgzQx7PvYbPOQUkDedbHEy7IxNd4CFxf%2FN1TkULMuEVzJ%2FYGgS4OFCF0IpqUhuJTul7WB5Hd%2BG5KAQ8os8YUQCDIfdUAt9p2oIYI54pyEEQQkf9hK3TIz%2Bln7PW1PrdnmyGmgFTJYqOWu

/**
 *
 */
public class Tools {
    private static final int DEF_DIV_SCALE = 10;
    public static String hamcsha1(byte[] data, byte[] key) {
        try {
            SecretKeySpec singingKey = new SecretKeySpec(key, "HmacSHA1");
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA1");
            //用给定密钥初始化 Mac 对象
            mac.init(singingKey);
            byte[] res = mac.doFinal(data);
            return byte2hex(res);
        } catch (Exception e) {
            return "";
        }
    }

    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp = "";
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append("0");
            }
            hs.append(stmp);
        }
        return hs.toString();
    }

    /**
     * @param v1
     * @param v2
     * @return
     * @Description 浮点数相加
     * @author jaily.zhang
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确的减法运算。
     *
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */

    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */

    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

    public static double div(double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }

    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The   scale   must   be   a   positive   integer   or   zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_DOWN).doubleValue();
    }

    public static String getToken(String accessKeyData, Long t, String secretKeyDate) {
        try {
            String data = accessKeyData + "," + t + "." + secretKeyDate;
            String s = hamcsha1(data.getBytes(), secretKeyDate.getBytes());
            String token = Base64.encodeToString(s.getBytes("utf-8"), Base64.NO_WRAP);
//            Log.e("error", "data:" + data);
//            Log.e("error", "secretKey:" + secretKeyDate);
//            Log.e("error", "token:" + token);
//            String token1 = Base64.encodeToString(s.getBytes("utf-8"), Base64.NO_WRAP);
//            Log.e("error", "token1:" + token1);
            return token;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param key     设置关键字
     * @param value   设置value
     * @param context
     */
    public static void setSharedPreferencesStrings(String key, String value, Context context) {
        SharedPreferences preferences = context.getSharedPreferences(Constant.SHAREPREFERENCEKEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * @param key         设置关键字
     * @param defaulvalue 默认value值
     * @param context
     * @return
     */
    public static String getSharedPreferencesStrings(String key, String defaulvalue, Context context) {
        SharedPreferences preferences = context.getSharedPreferences(Constant.SHAREPREFERENCEKEY, Context.MODE_PRIVATE);
        return preferences.getString(key, defaulvalue);
    }

    /**
     * @param key     设置关键字
     * @param value   设置value
     * @param context
     */
    public static void setSharedPreferencesboolen(String key, boolean value, Context context) {
        SharedPreferences preferences = context.getSharedPreferences(Constant.SHAREPREFERENCEKEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * @param key         设置关键字
     * @param defaulvalue 默认value值
     * @param context
     * @return
     */
    public static boolean getSharedPreferencesboolen(String key, boolean defaulvalue, Context context) {
        SharedPreferences preferences = context.getSharedPreferences(Constant.SHAREPREFERENCEKEY, Context.MODE_PRIVATE);
        return preferences.getBoolean(key, defaulvalue);
    }

    public static String timesTwo(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("MM.dd HH:mm");
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;
    }

    public static String timedate(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;
    }

    public static String timedateyyyy_MM_dd(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd");
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;
    }

    /**
     * Edittext 弹出键盘
     * @param activity
     * @param editText
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    /**
     * @param pullToRefreshListView
     * @Description 显示下拉scrollView刷新的那些文字label
     * @author jaily.zhang
     */
    public static void showScrollRefreshView(PullToRefreshScrollView pullToRefreshListView) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        Date now = new Date(System.currentTimeMillis());
        String label = sdf.format(now);
        ILoadingLayout startLabels = pullToRefreshListView.getLoadingLayoutProxy();
        startLabels.setPullLabel("最后更新 " + label);// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("加载中");// 刷新时
        startLabels.setReleaseLabel("最后更新 " + label);// 下来达到一定距离时，显示的提示
    }

    /**
     * @param pullToRefreshListView
     * @Description 显示下拉listview刷新的那些文字label
     * @author jaily.zhang
     */
    public static void showRefreshView(PullToRefreshListView pullToRefreshListView) {

        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        Date now = new Date(System.currentTimeMillis());
        String label = sdf.format(now);

        ILoadingLayout startLabels = pullToRefreshListView.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("最后更新 " + label);// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("加载中");// 刷新时
        startLabels.setReleaseLabel("最后更新 " + label);// 下来达到一定距离时，显示的提示

        ILoadingLayout endLabels = pullToRefreshListView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("最后更新 " + label);// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("加载中");// 刷新时
        endLabels.setReleaseLabel("最后更新 " + label);// 下来达到一定距离时，显示的提示

    }

    /**
     * 根据图片url获取网络图片
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static Bitmap getBitmap(String path) throws IOException {

        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.setDoInput(true);
//        conn.connect();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
            conn.disconnect();
            return bitmap;
        }
        return null;
    }

    /**
     * @param context
     * @param bm       图片
     * @param dir      文件夹路径
     * @param filename 文件名称
     * @Description 写图片到sd卡
     * @author jaily.zhang
     */
    public static void WriteImaToSdcard(Context context, Bitmap bm, String dir, String filename) {
        File cacheDir;
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), dir);
        else
            cacheDir = context.getCacheDir();
        if (!cacheDir.exists())
            cacheDir.mkdirs();
        File file = new File(cacheDir, filename);
        if (file.exists()) {
            file.delete();
        }

        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //正则判断手机号
    public static boolean isMobile(String number) {
        String num = "[1][358]\\d{9}";
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(number)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return number.matches(num);
        }
    }

    public static String formatDateTime(Date date) {
        String text;
        long dateTime = date.getTime();
        if (isSameDay(dateTime)) {
            Calendar calendar = GregorianCalendar.getInstance();
            if (inOneMinute(dateTime, calendar.getTimeInMillis())) {
                return "刚刚";
            } else if (inOneHour(dateTime, calendar.getTimeInMillis())) {
                return String.format("%d分钟之前", Math.abs(dateTime - calendar.getTimeInMillis()) / 60000);
            } else {
                calendar.setTime(date);
                int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
                if (hourOfDay > 17) {
                    text = "晚上 hh:mm";
                } else if (hourOfDay >= 0 && hourOfDay <= 6) {
                    text = "凌晨 hh:mm";
                } else if (hourOfDay > 11 && hourOfDay <= 17) {
                    text = "下午 hh:mm";
                } else {
                    text = "上午 hh:mm";
                }
            }
        } else if (isYesterday(dateTime)) {
            text = "昨天 HH:mm";
        } else if (isSameYear(dateTime)) {
            text = "M月d日 HH:mm";
        } else {
            text = "yyyy-M-d HH:mm";
        }

        // 注意，如果使用android.text.format.DateFormat这个工具类，在API 17之前它只支持adEhkMmszy
        return new SimpleDateFormat(text, Locale.CHINA).format(date);
    }


    public static String formatDateTimeMMDD(Date date) {
        // 注意，如果使用android.text.format.DateFormat这个工具类，在API 17之前它只支持adEhkMmszy
        return new SimpleDateFormat ("MM-dd").format(date);
    }

    public static String formatDateTimeyyyyMMDDhhmm(Date date) {
        // 注意，如果使用android.text.format.DateFormat这个工具类，在API 17之前它只支持adEhkMmszy
        return new SimpleDateFormat ("yyyy-MM-dd HH:mm").format(date);
    }

    public static String formatDateTimeyyyyMMDD(Date date) {
        // 注意，如果使用android.text.format.DateFormat这个工具类，在API 17之前它只支持adEhkMmszy
        return new SimpleDateFormat ("yyyy-MM-dd").format(date);
    }

    private static boolean isSameDay(long time) {
        long startTime = floorDay(Calendar.getInstance()).getTimeInMillis();
        long endTime = ceilDay(Calendar.getInstance()).getTimeInMillis();
        return time > startTime && time < endTime;
    }

    private static Calendar floorDay(Calendar startCal) {
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        startCal.set(Calendar.MILLISECOND, 0);
        return startCal;
    }
    private static Calendar ceilDay(Calendar endCal) {
        endCal.set(Calendar.HOUR_OF_DAY, 23);
        endCal.set(Calendar.MINUTE, 59);
        endCal.set(Calendar.SECOND, 59);
        endCal.set(Calendar.MILLISECOND, 999);
        return endCal;
    }

    private static boolean inOneMinute(long time1, long time2) {
        return Math.abs(time1 - time2) < 60000;
    }

    private static boolean inOneHour(long time1, long time2) {
        return Math.abs(time1 - time2) < 3600000;
    }

    private static boolean isYesterday(long time) {
        Calendar startCal;
        startCal = floorDay(Calendar.getInstance());
        startCal.add(Calendar.DAY_OF_MONTH, -1);
        long startTime = startCal.getTimeInMillis();

        Calendar endCal;
        endCal = ceilDay(Calendar.getInstance());
        endCal.add(Calendar.DAY_OF_MONTH, -1);
        long endTime = endCal.getTimeInMillis();
        return time > startTime && time < endTime;
    }

    private static boolean isSameYear(long time) {
        Calendar startCal;
        startCal = floorDay(Calendar.getInstance());
        startCal.set(Calendar.MONTH, Calendar.JANUARY);
        startCal.set(Calendar.DAY_OF_MONTH, 1);
        return time >= startCal.getTimeInMillis();
    }

    public static Date formatData(long timeStamp) {
        long timeLng=timeStamp;
        Date date = new Date(timeLng);
        return date;
    }

    /**
     * @param title   分享标题
     * @param url     分享url 地址
     * @param context 分享上下文
     * @Description 分享 事件处理
     * @author jaily.zhang
     */
    public static void showShare(String title, String url, String content, Context context) {
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
//        oks.setText("分享自大数据投资App《智投》");
        oks.setText(content);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        File cacheDir;
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), Constant.wsc_photo);
        else
            cacheDir = context.getCacheDir();
        final File file = new File(cacheDir, "taohua.png");
        oks.setImagePath(file.getPath());// 确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(context.getResources().getString(R.string.app_name));
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(context.getResources().getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);
        // 启动分享GUI
        oks.show(context);
    }

    public static String  unicodeToString(String unicodeString)
    {
        try {
            byte[] utf8Bytes = unicodeString.getBytes("UTF8");
            String country = new String(utf8Bytes,"UTF8");
            return country;
        }catch (Exception e)
        {
            return "";
        }
    }


}
